import {
  Body,
  Controller,
  Delete,
  Get,
  Logger,
  Param,
  Post,
  Put,
  Req,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiParam,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { Request } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { User } from '../entities/user.entity';
import { UsersService } from './users.service';

// 定义包含用户信息的请求接口
interface RequestWithUser extends Request {
  user: {
    userId: number;
    username: string;
  };
}

@ApiTags('users')
@Controller('users')
export class UsersController {
  private readonly logger = new Logger(UsersController.name);

  constructor(private readonly usersService: UsersService) {}

  @Get()
  @ApiOperation({
    summary: '获取所有用户',
    description: '返回系统中所有用户的列表',
  })
  @ApiResponse({ status: 200, description: '成功获取用户列表', type: [User] })
  findAll(): Promise<User[]> {
    return this.usersService.findAll();
  }

  @Get('profile')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({
    summary: '获取当前用户资料',
    description: '返回当前登录用户的详细信息',
  })
  @ApiResponse({ status: 200, description: '成功获取用户资料', type: User })
  @ApiResponse({ status: 401, description: '未授权' })
  async getProfile(@Req() request: RequestWithUser): Promise<User | null> {
    // 添加日志，便于调试
    this.logger.debug(`Request user object: ${JSON.stringify(request.user)}`);

    // 从请求对象中获取用户ID
    const userId = request.user?.userId;
    this.logger.debug(`Extracted userId: ${userId}`);

    // 检查用户ID是否有效
    if (!userId || isNaN(Number(userId))) {
      this.logger.error(`Invalid userId: ${userId}`);
      throw new UnauthorizedException('未找到有效的用户信息');
    }

    return this.usersService.findOne(Number(userId));
  }

  @Get(':id')
  @ApiOperation({ summary: '获取指定用户', description: '根据ID获取用户详情' })
  @ApiParam({ name: 'id', description: '用户ID' })
  @ApiResponse({ status: 200, description: '成功获取用户详情', type: User })
  @ApiResponse({ status: 404, description: '用户不存在' })
  findOne(@Param('id') id: string): Promise<User | null> {
    return this.usersService.findOne(+id);
  }

  @Post()
  @ApiOperation({ summary: '创建用户', description: '创建新的用户' })
  @ApiResponse({ status: 201, description: '成功创建用户', type: User })
  create(@Body() user: Partial<User>): Promise<User> {
    return this.usersService.create(user);
  }

  @Put(':id')
  @ApiOperation({ summary: '更新用户', description: '更新指定ID的用户信息' })
  @ApiParam({ name: 'id', description: '用户ID' })
  @ApiResponse({ status: 200, description: '成功更新用户' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async update(
    @Param('id') id: string,
    @Body() user: Partial<User>,
  ): Promise<void> {
    await this.usersService.update(+id, user);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除用户', description: '删除指定ID的用户' })
  @ApiParam({ name: 'id', description: '用户ID' })
  @ApiResponse({ status: 200, description: '成功删除用户' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async remove(@Param('id') id: string): Promise<void> {
    await this.usersService.remove(+id);
  }
}
